<script setup>
// 引入 watch 函数
import { watch, ref, computed } from 'vue';

// 定义响应式数据：price
const price = ref(9);
// 数量
const quantity = ref(100);
const changePrice = () => {
  // console.log('组件渲染完毕， changePrice');
  price.value = price.value + 1;
};
const changeQuantity = () => {
  // console.log('组件渲染完毕， changePrice');
  quantity.value = quantity.value + 10;
};

// const computedCount = computed(() => {
//   console.log('组件渲染完毕， computed');
//   return 100;
// });

// 调用 watch 函数监听数据变化
// watch(price, (newPrice, oldPrice) => {
//   console.log('组件渲染完毕， watch');
//   console.log('价格变化了', newPrice, oldPrice);
// });

// 监听价格或数量
// watch([price, quantity], (newValue, oldValue) => {
//   console.log('价格或数量变化了', newValue, oldValue);
// });

// 对象数据
const user = ref({
  name: 'bingo',
  info: {
    gender: '男',
    age: 18,
  },
});
// 侦听user对象的name属性
watch(
  () => user.value.name,
  (newValue, oldValue) => {
    console.log('user.value.name变化了', newValue, oldValue);
  }
);
// 侦听对象的变化
watch(
  () => user.value.info,
  (newValue, oldValue) => {
    console.log('user.value.info变化了', newValue, oldValue);
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <div>
    <!-- template中直接使用 -->
    <!-- <h1>{{ computedCount }}</h1> -->
    <h1>价格：{{ price }} 数量：{{ quantity }}</h1>
    <button @click="changePrice">改价格</button>
    <button @click="changeQuantity">改数量</button>
    <hr />
    <h1>{{ user.name }}</h1>
    <button @click="user.name += '变'">改name</button>
    <hr />
    <h1>{{ user.info.age }}</h1>
    <button @click="user.info.age += 1">改年龄</button>
    <hr />
    <h1>{{ user.info.gender }}</h1>
    <button @click="user.info.gender += '变'">改性别</button>
    <hr />
    <button @click="user.info = { gender: 'xxx', age: 100 }">改对象</button>
  </div>
</template>
